package folderLogger.outputFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class OutputFileWriter extends OutputWriter
{
	private String outputFolder;
	private boolean isInitialized;
	private final String indexName = "index";
	
	public OutputFileWriter(String outputFolder, OutputFileFormat type, String resourcesFolder)
	{
		super(type, resourcesFolder);
		this.outputFolder = outputFolder;
		isInitialized = false;
	}
	
	/**
	 * Initialises the output file.
	 * 
	 * @return 0 iff file was initialised successfully. negative value otherwise.
	 */
	@Override
	public int InitializeIndexFile()
	{
		if(outputFolder == null)
		{
			return -10;
		}
		String fileName = String.format("%s\\%s.%s", outputFolder, indexName, type.toString().toLowerCase());
		File actualFile = new File(fileName);
		if(actualFile.exists())
		{
			return -1;
		}
		try {
			outputFile = new PrintStream(actualFile);
		} catch (FileNotFoundException e) {
			return -2;
		}

		if(outputFile == null)
		{
			return -3;
		}
		isInitialized = true;
		return 0;
	}
	
	@Override
	public void close()
	{
		if(isInitialized)
		{
			//	flush and close!
			outputFile.close();
		}
	}

	@Override
	protected boolean ExportDataStream(String currentName, String currentData) {
		
		File dir = new File(String.format("%s\\%s", outputFolder, resourcesFolder));
		if(!dir.exists() || !dir.isDirectory())
		{
			if(!dir.mkdirs())
			{
				return false;
			}
		}
		
		String fileName = String.format("%s\\%s", outputFolder, currentName);
		File actualFile = new File(fileName);
		if(actualFile.exists())
		{
			return false;
		}
		try {
			outputFile = new PrintStream(actualFile);
		} catch (FileNotFoundException e) {
			return false;
		}

		if(outputFile == null)
		{
			return false;
		}
		outputFile.println(currentData);
		outputFile.close();
		
		return true;
	}


}
